//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Galleries;
using CommunityServer.Galleries.Components;
using CA = ComponentArt.Web.UI;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using HelpIcon = CommunityServer.ControlPanel.Controls.HelpIcon;

namespace CommunityServer.ControlPanel.Photos
{
	/// <summary>
	///		Summary description for CommentListControl.
	/// </summary>
	public class CommentListControl : BaseGalleryGridControl
	{

		#region Child Controls

		protected CA.Grid Grid1;
		protected IButton ActionButton;
		protected HelpIcon Helpicon1;
		protected ResourceControl FeedbackFilterLabel;
		protected DropDownList filterPost;
		protected DropDownList filterPublished;
		protected IButton FilterButton;
		protected Modal Modal1;
		protected DropDownList ActionList;

		#endregion

		private void Page_Load(object sender, EventArgs e)
		{
			//overload the row size because this is a two line grid
			this.CurrentGridRowSize = 2;

			if(!Page.IsPostBack && !GalleryPage.IsCallBack)
			{
				BindFilters();
				buildGrid();
				Grid.DataBind();
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			this.Grid.ItemCheckChanged += new CA.Grid.ItemCheckChangedEventHandler(this.Grid_ItemCheckChanged);
			this.Grid.DeleteCommand += new CA.Grid.GridItemEventHandler(this.Grid_DeleteCommand);
			this.ActionButton.Click += new EventHandler(this.ActionButton_Click);
			this.FilterButton.Click += new EventHandler(this.FilterButton_Click);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new EventHandler(this.Page_Load);

		}


		#endregion

		private void BindFilters()
		{
			ActionButton.Attributes.Add("onclick","return validate_click();");
			ActionList.Items.Add(new ListItem(Components.ResourceManager.GetString("CP_Moderate_Actions"),"-1"));
			ActionList.Items.Add(new ListItem(Components.ResourceManager.GetString("CP_Moderate_Approve"),"0"));
			ActionList.Items.Add(new ListItem(Components.ResourceManager.GetString("CP_Moderate_Disapprove"),"1"));
			ActionList.Items.Add(new ListItem(Components.ResourceManager.GetString("CP_Moderate_Delete"),"2"));

			ActionButton.Text = Components.ResourceManager.GetString("CP_Moderate_Action");
			filterPublished.Items.Add(new ListItem(Components.ResourceManager.GetString("Feedback_SelectAll"), ((int)GalleryPostPublishedFilter.All).ToString()));
			filterPublished.Items.Add(new ListItem(Components.ResourceManager.GetString("Feedback_FilterPublished"), ((int)GalleryPostPublishedFilter.Published).ToString()));
			filterPublished.Items.Add(new ListItem(Components.ResourceManager.GetString("Feedback_FilterNotPublished"), ((int)GalleryPostPublishedFilter.NotPublished).ToString()));
			// Retrieve list of recent blog posts
			GalleryThreadQuery query = new GalleryThreadQuery();
			query.SectionID = this.CurrentGallery.SectionID;
			query.ApplicationPostType = GalleryPostType.Image;
			query.GalleryThreadType = GalleryThreadType.Recent;
			query.IncludeCategories = false;
			query.PublishedFilter = GalleryPostPublishedFilter.All;
			query.PageSize = 20;
			query.SortOrder = SortOrder.Descending;
			query.SortBy = GalleryThreadSortBy.ThreadDate;
			ThreadSet threads = GalleryPosts.GetPictures(query,false) ;
			// Insert default "All" item
			filterPost.Items.Add(new ListItem(ResourceManager.GetString("Feedback_FilterAll"), "-1"));
			foreach (GalleryPost post in threads.Threads)
			{
				filterPost.Items.Add(new ListItem(Globals.HtmlDecode(post.Subject), Convert.ToString(post.PostID)));
			}

			// Check if preselected values of the filter DropDownLists were passed in the URL
			CSContext context = CSContext.Current;
			ListItem li = null;

			int pid = context.GetIntFromQueryString("pid",-1);

			if(pid > -1)
			{
				li = filterPost.Items.FindByValue(pid.ToString());
				if(li != null)
				{
					li.Selected = true;
                
				}
			}

  		this.GridMode = CA.GridRunningMode.Callback;    


            

			li = filterPublished.Items.FindByValue(context.GetIntFromQueryString("ip", (int)BlogPostPublishedFilter.All).ToString());
			if(li != null)
				li.Selected = true;
            
		}
		private void FilterButton_Click(object sender, EventArgs e)
		{
			string url  = "{0}?pid={1}&ip={2}";
			url = string.Format(url,Request.Path,filterPost.SelectedValue,filterPublished.SelectedValue);
			Response.Redirect(url);
		}

		private void Grid_DeleteCommand(object sender, CA.GridItemEventArgs e)
		{
			int postID = Globals.SafeInt(e.Item["PostID"].ToString(), 0) ;
			DeletePost(postID);
		}

		private void DeletePost(int postID)
		{
			GalleryPosts.DeleteComment(postID);
		}

		private void PostIsApproved(int postID, bool isApproved)
		{
			if(isApproved)
				GalleryDataProvider.Instance().ApprovePost(postID, CSContext.Current.UserID);
			else
				throw new NotImplementedException("No way to disapprove a gallery post yet"); 

		}


		protected override void buildGrid()
		{
			CSContext context = CSContext.Current;

			int parentid = context.GetIntFromQueryString("pid",-1);
			GalleryThreadQuery query = new GalleryThreadQuery();
			query.SectionID = CurrentGallery.SectionID;
			
			if(this.GridMode == CA.GridRunningMode.Callback)
			{
				query.PageSize = this.DefaultPageSize;
				query.PageIndex = Grid.CurrentPageIndex;
				Grid.ManualPaging = true;
			}

			query.ParentID = parentid;
			query.ApplicationPostType = GalleryPostType.Comment | GalleryPostType.Trackback;
			query.PublishedFilter = (GalleryPostPublishedFilter)context.GetIntFromQueryString("ip", (int)GalleryPostPublishedFilter.All);
			query.SortOrder = SortOrder.Descending;

			int postID = context.GetIntFromQueryString("pid",-1); 
			if(postID > -1)
				query.ParentID = postID;

			ThreadSet ts = GalleryPosts.GetPictures(query, false);

			Grid.DataSource = ts.Threads;

			this.RecordCount = ts.TotalRecords;


			base.buildGrid();

		}

		public void Grid_ItemCheckChanged(object sender, CA.GridItemCheckChangedEventArgs e)
		{
			//This event is raised on every callback. We only need to handle it on a postback/click
			if(!this.GalleryPage.IsCallBack && e.Checked) 
			{
				int postID = Globals.SafeInt(e.Item["PostID"].ToString(), 0) ;
				switch (ActionList.SelectedIndex)
				{
					case 1:
						if(!bool.Parse(e.Item["IsApproved"].ToString()))
							PostIsApproved(postID, true);
						break;
					case 2:
						if(bool.Parse(e.Item["IsApproved"].ToString()))
							PostIsApproved(postID, false);
						break;
					case 3:
						DeletePost(postID);
						break;
				}

			}
			
		}

		public void ActionButton_Click(object sender, EventArgs e)
		{
			//HACK: For now lets redirect the user to the current page to clear any client side checkmarks
			Response.Redirect(HttpContext.Current.Request.Url.ToString()) ;

			//This event should fire after the ItemCheckChanged and 
			// is responsible for binding any data changes back to the grid
			buildGrid();
			Grid.DataBind();
		}

		protected override void ConfigureGrid()
		{
			AddGridCheckMarkTemplate("IsApproved");
			AddGridPublishedDateTemplate("AuthorUrl", "DisplayName", "FormattedPostDate");
			AddGridPagerTemplate("Subject", "DisplayName", "FormattedPostDate","IsApproved");
		}



	}
}
